import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:shirne_dialog/shirne_dialog.dart';
import 'package:zxing_widget/qrcode.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int progress = 0;
  int total = 0;
  bool isGenerating = false;

  final contentController = TextEditingController(
    text: 'https://htobao.com/u.php?q=R{id}',
  );
  final keywordController = TextEditingController(text: 'id');
  final startController = TextEditingController(text: '1');
  final endController = TextEditingController(text: '100');
  final lengthController = TextEditingController(text: '8');
  final sizeController = TextEditingController(text: '500');

  final labelWidth = 120.0;

  void startGenerate() async {
    if (isGenerating) return;
    if (contentController.text.isEmpty) {
      MyDialog.toast('请填写生成内容');
      return;
    }
    final start = int.tryParse(startController.text);
    final end = int.tryParse(endController.text);
    final length = int.tryParse(lengthController.text);
    final size = int.tryParse(sizeController.text);
    if (start == null) {
      MyDialog.toast('请填写起始ID');
      return;
    }
    if (end == null) {
      MyDialog.toast('请填写结束ID');
      return;
    }
    if (end <= start) {
      MyDialog.toast('结束ID必须大于起始ID');
      return;
    }
    if (length == null || length < 0) {
      MyDialog.toast('ID长度不能为负数');
      return;
    }
    if (size == null || size < 50) {
      MyDialog.toast('二维码尺寸需要大于50');
      return;
    }
    setState(() {
      total = end - start + 1;
      progress = 0;
      isGenerating = true;
    });
    final baseText = contentController.text;

    final path = '${Directory.current.path}/qrcodes';
    try {
      Directory(path).createSync(recursive: true);

      for (var i = start; i <= end; i++) {
        var key = '$i';
        if (length > 0) {
          key = key.padLeft(length, '0');
        }
        final text = baseText.replaceAll('{${keywordController.text}}', key);
        var qrcode =
            await QrcodePainter(text).toImage(Size.square(size.toDouble()));
        final byte = await qrcode.toByteData(format: ImageByteFormat.png);
        if (byte == null) {
          MyDialog.toast('二维码生成失败');
          return;
        }
        File('$path/$key.png').writeAsBytesSync(byte.buffer.asUint8List());

        setState(() {
          progress++;
        });
      }
    } catch (e) {
      MyDialog.toast('二维码生成失败');
    } finally {
      setState(() {
        isGenerating = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        constraints: const BoxConstraints(maxWidth: 980),
        alignment: Alignment.topCenter,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Row(
                children: [
                  Container(
                    width: labelWidth,
                    alignment: Alignment.centerRight,
                    child: const Text('内容: '),
                  ),
                  Expanded(
                    child: TextField(
                      controller: contentController,
                      decoration: const InputDecoration(),
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  Container(
                    width: labelWidth,
                    alignment: Alignment.centerRight,
                    child: const Text('替换词: '),
                  ),
                  Expanded(
                    child: TextField(
                      controller: keywordController,
                      decoration: const InputDecoration(),
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  Container(
                    width: labelWidth,
                    alignment: Alignment.centerRight,
                    child: const Text('ID区间: '),
                  ),
                  Expanded(
                    child: TextField(
                      controller: startController,
                      keyboardType: TextInputType.number,
                      textAlign: TextAlign.center,
                      decoration: const InputDecoration(),
                    ),
                  ),
                  const Text('-'),
                  Expanded(
                    child: TextField(
                      controller: endController,
                      keyboardType: TextInputType.number,
                      textAlign: TextAlign.center,
                      decoration: const InputDecoration(),
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  Container(
                    width: labelWidth,
                    alignment: Alignment.centerRight,
                    child: const Text('ID长度: '),
                  ),
                  Expanded(
                    child: TextField(
                      controller: lengthController,
                      decoration: const InputDecoration(),
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  Container(
                    width: labelWidth,
                    alignment: Alignment.centerRight,
                    child: const Text('二维码尺寸: '),
                  ),
                  Expanded(
                    child: TextField(
                      controller: sizeController,
                      decoration: const InputDecoration(),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              if (isGenerating || total > 0)
                Padding(
                  padding: const EdgeInsets.only(bottom: 16),
                  child: Text(
                    '${isGenerating ? '正在' : '已'}生成 $progress/$total',
                  ),
                ),
              ElevatedButton(
                onPressed: isGenerating ? null : startGenerate,
                child: const Text('开始生成'),
              ),
            ],
          ),
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
